//
//  SettingViewController.m
//  Riese
//
//  Created by air on 2019/10/26.
//  Copyright © 2019 wangjinyu. All rights reserved.
//

#import "SettingViewController.h"
#import "SettingCell.h"
#import "SettingCell01.h"
#import "SettingCell02.h"
#import <BRStringPickerView.h>
#import <MMAlertView.h>

#import "SaveSettingViewController.h"
#import "NSBundle+Language.h"

@interface SettingViewController () <UITableViewDelegate, UITableViewDataSource> {
    UIButton *saveBtn;
}

@property (nonatomic, strong) UITableView *mainTable;
@property (nonatomic, strong) NSArray *dataArr;

@property (nonatomic, strong) NSString *languageStr;
@property (nonatomic, strong) NSString *softStr;
@property (nonatomic, strong) NSString *lengthStr;
@property (nonatomic, strong) NSString *soundStr;
@property (nonatomic, strong) NSString *isClear;

@end

@implementation SettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = kColor(243, 243, 243);
    self.navigationItem.title = NSLocalizedString(@"Settings", nil);
    
    self.languageStr = @"1";
    self.lengthStr = @"0";
    if (defaults(@"DeviceSound")) {
        if ([defaults(@"DeviceSound") isEqualToString:@"1"]) {
            self.soundStr = @"0";
        }
        else {
            self.soundStr = @"1";
        }
    }
    else {
        self.soundStr = @"1";
    }
    
    if (defaults(@"DeviceLanguage")) {
        NSArray *localizedArr = @[@"Chinese", @"English", @"意大利语", @"French", @"波兰语", @"German", @"日语"];
        for (int i = 0; i < localizedArr.count; i++) {
            if ([defaults(@"DeviceLanguage") isEqualToString:localizedArr[i]]) {
                if (i < 3) {
                    self.languageStr = [NSString stringWithFormat:@"%d", i];
                }
                else if (i == 3) {
                    self.languageStr = @"4";
                }
                else if (i == 4) {
                    self.languageStr = @"7";
                }
                else if (i == 5) {
                    self.languageStr = @"13";
                }
                else {
                    self.languageStr = @"12";
                }
                break;
            }
        }
    }
    
    if (defaults(@"DeviceLength")) {
        NSString *str = defaults(@"DeviceLength");
        if ([str isEqualToString:@"10s"]) {
            self.lengthStr = @"0";
        }
        else if ([str isEqualToString:@"15s"]) {
            self.lengthStr = @"1";
        }
        else {
            self.lengthStr = @"2";
        }
    }
    
    self.isClear = @"0";
    self.softStr = NSLocalizedString(@"English", nil);
    
    NSString *currentLanguage = defaults(@"AppLanguagesKey");
    if (!currentLanguage) {
        NSString *language = [self getCurrentLanguage];
        if (![language isEqualToString:@"zh-Hans"] && ![language isEqualToString:@"en"] && ![language isEqualToString:@"de"] && ![language isEqualToString:@"fr"]) {
            currentLanguage = @"en";
        }
        else {
            currentLanguage = language;
        }
    }
    
    if ([currentLanguage isEqualToString:@"zh-Hans"]) {
        self.softStr = NSLocalizedString(@"Chinese", nil);
    }
    else if ([currentLanguage isEqualToString:@"en"]) {
        self.softStr = NSLocalizedString(@"English", nil);
    }
    else if ([currentLanguage isEqualToString:@"de"]) {
        self.softStr = NSLocalizedString(@"German", nil);
    }
    else {
        self.softStr = NSLocalizedString(@"French", nil);
    }
    
    NSString *deviceStr = defaults(@"DeviceLanguage") ? defaults(@"DeviceLanguage") : @"English";
    
    self.dataArr = @[
        @[@{
              @"title": NSLocalizedString(@"Device Language", nil),
              @"content": NSLocalizedString(deviceStr, nil)
        },@{
              @"title": NSLocalizedString(@"Length of Recording", nil),
              @"content": defaults(@"DeviceLength") ? defaults(@"DeviceLength") : @"10s"
        },@{
              @"title": NSLocalizedString(@"Heartbeat Sound", nil),
              @"content": @""
        },@{
              @"title": NSLocalizedString(@"Clear Memory", nil),
              @"subTitle": NSLocalizedString(@"Old recordings in your device", nil),
              @"content": @""
        }],
        @[@{
              @"title": NSLocalizedString(@"Software Language", nil),
              @"content": self.softStr
        }, @{
              @"title": NSLocalizedString(@"Gain", nil),
              @"content": defaults(@"gain")
        }, @{
              @"title": NSLocalizedString(@"Speed", nil),
              @"content": defaults(@"speed")
        }
        ]];
    [self makeNav];
    [self makeUI];
}

- (NSString *)getCurrentLanguage
{
    NSArray *languages = [NSLocale preferredLanguages];
    NSString *currentLanguage = [languages objectAtIndex:0];
    NSLog( @"%@" , currentLanguage);
    
    if ([currentLanguage containsString:@"-CN"]) {
        return [currentLanguage substringToIndex:(currentLanguage.length - 3)];
    }
    else {
        return currentLanguage;
    }
}

- (void)makeNav {
    saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    saveBtn.frame = CGRectMake(0, 0, 70, kNavHeight);
    [saveBtn setTitle:NSLocalizedString(@"Save", nil) forState:UIControlStateNormal];
    [saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    saveBtn.titleLabel.font = kRegularFont(14);
    [saveBtn addTarget:self action:@selector(saveBtnClick) forControlEvents:UIControlEventTouchUpInside];
    saveBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:saveBtn];
}

- (void)makeUI {
    self.mainTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.mainTable.backgroundColor = [UIColor clearColor];
    self.mainTable.delegate = self;
    self.mainTable.dataSource = self;
    self.mainTable.showsVerticalScrollIndicator = NO;
    self.mainTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.mainTable];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.row == 2) {
        // heartbeat sound
        NSString *cellIdentifier = @"SettingCell01";
        SettingCell01 *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (!cell) {
            cell = [[NSBundle mainBundle] loadNibNamed:cellIdentifier owner:self options:nil].firstObject;
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell.soundSwitch addTarget:self action:@selector(soundClick:) forControlEvents:UIControlEventValueChanged];
        
        return cell;
    }
    else if (indexPath.section == 0 && indexPath.row == 3) {
        NSString *cellIdentifier = @"SettingCell02";
        SettingCell02 *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (!cell) {
            cell = [[NSBundle mainBundle] loadNibNamed:cellIdentifier owner:self options:nil].firstObject;
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }
    else {
        NSString *cellIdentifier = @"SettingCell";
        SettingCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (!cell) {
            cell = [[NSBundle mainBundle] loadNibNamed:cellIdentifier owner:self options:nil].firstObject;
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.dataDic = self.dataArr[indexPath.section][indexPath.row];
        
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.row == 3) {
        return 73;
    }
    else {
        return 65;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.dataArr[section] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
    view.backgroundColor = kColor(243, 243, 243);
    
    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.row == 0) {
        // device language  0  1  13  4
        NSArray *dataSource = @[NSLocalizedString(@"Chinese", nil), NSLocalizedString(@"English", nil), NSLocalizedString(@"German", nil), NSLocalizedString(@"French", nil)];
        NSArray *localizedArr = @[@"Chinese", @"English", @"German", @"French"];
        NSInteger index = 0;
        if ([self.languageStr integerValue] < 2) {
            index = [self.languageStr integerValue];
        }
        else if ([self.languageStr integerValue] == 4) {
            index = 3;
        }
        else {
            index = 2;
        }
        
        NSString *defaultStr = dataSource[index];
        
        //        [BRStringPickerView showStringPickerWithTitle:@"" dataSource:dataSource defaultSelValue:defaultStr resultBlock:^(id selectValue) {
        //            for (int i = 0; i < dataSource.count; i++) {
        //                if ([selectValue isEqual:dataSource[i]]) {
        //                    setDefaults(localizedArr[i], @"DeviceLanguage");
        //                    if (i < 2) {
        //                        self.languageStr = [NSString stringWithFormat:@"%d", i];
        //                    }
        //                    else if (i == 2) {
        //                        self.languageStr = @"13";
        //                    }
        //                    else if (i == 3) {
        //                        self.languageStr = @"4";
        //                    }
        //                    break;
        //                }
        //            }
        //            [self reloadData];
        //        }];
        
        int aaa = 0;
        for (int i = 0; i<dataSource.count; i++) {
            if ([dataSource[i] isEqual:defaultStr]) {
                aaa =  i;
            }
        }
        
        
        
        [BRStringPickerView showPickerWithTitle:@"" dataSourceArr:dataSource selectIndex:aaa resultBlock:^(BRResultModel * _Nullable resultModel) {
            for (int i = 0; i < dataSource.count; i++) {
                if ([resultModel.value isEqual:dataSource[i]]) {
                    setDefaults(localizedArr[i], @"DeviceLanguage");
                    if (i < 2) {
                        self.languageStr = [NSString stringWithFormat:@"%d", i];
                    }
                    else if (i == 2) {
                        self.languageStr = @"13";
                    }
                    else if (i == 3) {
                        self.languageStr = @"4";
                    }
                    break;
                }
            }
            [self reloadData];
        }];
    }
    else if (indexPath.section == 0 && indexPath.row == 1) {
        // length of recording  0  1  2
        NSArray *dataSource = @[@"10s", @"15s", @"30s"];
        //        NSString *defaultStr = dataSource[[self.lengthStr integerValue]];
        //        [BRStringPickerView showStringPickerWithTitle:@"" dataSource:dataSource defaultSelValue:defaultStr resultBlock:^(id selectValue) {
        //            for (int i = 0; i < dataSource.count; i++) {
        //                if ([selectValue isEqual:dataSource[i]]) {
        //                    self.lengthStr = [NSString stringWithFormat:@"%d", i];
        //                    setDefaults(selectValue, @"DeviceLength");
        //                    break;
        //                }
        //            }
        //            [self reloadData];
        //        }];
        
        [BRStringPickerView showPickerWithTitle:@"" dataSourceArr:dataSource selectIndex:[self.lengthStr integerValue] resultBlock:^(BRResultModel * _Nullable resultModel) {
            for (int i = 0; i < dataSource.count; i++) {
                if ([resultModel.value isEqual:dataSource[i]]) {
                    self.lengthStr = [NSString stringWithFormat:@"%d", i];
                    setDefaults(resultModel.value, @"DeviceLength");
                    break;
                }
            }
            [self reloadData];
        }];
    }
    else if (indexPath.section == 0 && indexPath.row == 2) {
        // heartbeat sound
    }
    else if (indexPath.section == 0 && indexPath.row == 3) {
        // clear memory
        NSArray *items = @[MMItemMake(NSLocalizedString(@"cancel", nil), MMItemTypeNormal, nil), MMItemMake(NSLocalizedString(@"sure", nil), MMItemTypeNormal, ^(NSInteger index) {
            //            [SVProgressHUD show];
            //            [self removeDataBase];
            self.isClear = @"1";
        })];
        [[[MMAlertView alloc] initWithTitle:@"" detail:[NSString stringWithFormat:@"\n%@", NSLocalizedString(@"Are you sure to delete?", nil)] items:items] show];
    }
    else if (indexPath.section == 1 && indexPath.row == 0) {
        // software language
        NSArray *dataSource = @[NSLocalizedString(@"Chinese", nil), NSLocalizedString(@"English", nil), NSLocalizedString(@"German", nil), NSLocalizedString(@"French", nil)];
        NSString *defaultStr = self.softStr;
//        [BRStringPickerView showStringPickerWithTitle:@"" dataSource:dataSource defaultSelValue:defaultStr resultBlock:^(id selectValue) {
        int aaa = 0;
        for (int i = 0; i<dataSource.count; i++) {
            if ([dataSource[i] isEqual:self.softStr]) {
                aaa =  i;
            }
        }
        
        
        [BRStringPickerView showPickerWithTitle:@"" dataSourceArr:dataSource selectIndex:aaa resultBlock:^(BRResultModel * _Nullable resultModel) {

            for (int i = 0; i < dataSource.count; i++) {
                if ([resultModel.value isEqual:dataSource[i]]) {
                    if (i == 0) {
                        [NSBundle setLanguage:@"zh-Hans"];
                        self.softStr = NSLocalizedString(@"Chinese", nil);
                    }
                    else if (i == 1) {
                        [NSBundle setLanguage:@"en"];
                        self.softStr = NSLocalizedString(@"English", nil);
                    }
                    else if (i == 2) {
                        [NSBundle setLanguage:@"de"];
                        self.softStr = NSLocalizedString(@"German", nil);
                    }
                    else {
                        [NSBundle setLanguage:@"fr"];
                        self.softStr = NSLocalizedString(@"French", nil);
                    }
                    break;
                }
            }
            [self reloadData];
        }];
    }
    else if (indexPath.section == 1 && indexPath.row == 1) {
        // gain
        NSArray *dataSource = @[@"5mm/mV", @"10mm/mV", @"20mm/mV"];
        NSString *defaultStr = [defaults(@"gain") length] > 0 ? defaults(@"gain") : @"10mm/mV";
//        [BRStringPickerView showStringPickerWithTitle:@"" dataSource:dataSource defaultSelValue:defaultStr resultBlock:^(id selectValue) {
               [BRStringPickerView showPickerWithTitle:@"" dataSourceArr:dataSource selectIndex:0 resultBlock:^(BRResultModel * _Nullable resultModel) {
                   setDefaults(resultModel.value, @"gain");
            [self reloadData];
        }];
    }
    else if (indexPath.section == 1 && indexPath.row == 2) {
        // speed
        NSArray *dataSource = @[@"12.5mm/s", @"25mm/s", @"50mm/s"];
        NSString *defaultStr = [defaults(@"speed") length] > 0 ? defaults(@"speed") : @"25mm/s";
//        [BRStringPickerView showStringPickerWithTitle:@"" dataSource:dataSource defaultSelValue:defaultStr resultBlock:^(id selectValue) {
        [BRStringPickerView showPickerWithTitle:@"" dataSourceArr:dataSource selectIndex:0 resultBlock:^(BRResultModel * _Nullable resultModel) {

            setDefaults(resultModel.value, @"speed");
            [self reloadData];
        }];
    }
}

- (void)removeDataBase {
    
    NSString * docsdir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString * path = [docsdir stringByAppendingPathComponent:@"DeviceData.sqlite"];
    
    NSFileManager*fileManager = [NSFileManager defaultManager];
    
    if (![fileManager fileExistsAtPath:path]) {
        
        return;
        
    }
    
    //    NSEnumerator* chileFilesEnumerator = [[fileManager subpathsAtPath:path]objectEnumerator];
    
    //    NSString* fileName;
    //
    //    while ((fileName = [chileFilesEnumerator nextObject]) !=nil) {
    //
    //        NSString * docsdir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    //        NSString * path = [docsdir stringByAppendingPathComponent:@"DeviceData.sqlite"];
    //
    //        [fileManager removeItemAtPath:path error:NULL];
    //
    //    }
    
    [fileManager removeItemAtPath:path error:NULL];
    
    [SVProgressHUD dismiss];
    [YJProgressHUD showMessage:NSLocalizedString(@"Delete successfully", nil) inView:self.view];
}

- (void)soundClick: (UISwitch *)soundSwitch {
    if (soundSwitch.on) {
        self.soundStr = @"0";
        setDefaults(@"0", @"DeviceSound");
    }
    else {
        self.soundStr = @"1";
        setDefaults(@"1", @"DeviceSound");
    }
}

- (void)saveBtnClick {
    SaveSettingViewController *vc = [SaveSettingViewController new];
    vc.languageStr = self.languageStr;
    vc.lengthStr = self.lengthStr;
    vc.soundStr = self.soundStr;
    vc.isClear = self.isClear;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)reloadData {
    self.navigationItem.title = NSLocalizedString(@"Settings", nil);
    [saveBtn setTitle:NSLocalizedString(@"Save", nil) forState:UIControlStateNormal];
    
    NSArray *languageArr = @[NSLocalizedString(@"Chinese", nil), NSLocalizedString(@"English", nil), NSLocalizedString(@"German", nil), NSLocalizedString(@"French", nil)];
    NSArray *lengthArr = @[@"10s", @"15s", @"30s"];
    
    NSInteger index = 0;
    // 0  1  13  4
    if ([self.languageStr integerValue] < 2) {
        index = [self.languageStr integerValue];
    }
    else if ([self.languageStr integerValue] == 4) {
        index = 3;
    }
    else if ([self.languageStr integerValue] == 13) {
        index = 2;
    }
    
    self.dataArr = @[
        @[@{
              @"title": NSLocalizedString(@"Device Language", nil),
              @"content": languageArr[index]
        },@{
              @"title": NSLocalizedString(@"Length of Recording", nil),
              @"content": lengthArr[[self.lengthStr integerValue]]
        },@{
              @"title": NSLocalizedString(@"Heartbeat Sound", nil),
              @"content": @""
        },@{
              @"title": NSLocalizedString(@"Clear Memory", nil),
              @"subTitle": NSLocalizedString(@"Old recordings in your device", nil),
              @"content": @""
        }],
        @[@{
              @"title": NSLocalizedString(@"Software Language", @"nil"),
              @"content": self.softStr
        }, @{
              @"title": NSLocalizedString(@"Gain", nil),
              @"content": defaults(@"gain")
        }, @{
              @"title": NSLocalizedString(@"Speed", nil),
              @"content": defaults(@"speed")
        }
        ]];
    
    [self.mainTable reloadData];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
